package com.rzy.f_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gaopeng
 * @time 2021/05/20 15:24:55
 * synchronized是jvm级别的锁，锁的释放，由jvm保证
 * lock释放锁，必须手动释放
 */


public class App6 {

    static class T implements Runnable {

        private Lock lock = new ReentrantLock();
        private Object obj;

        public T(Object obj) {
            this.obj = obj;
        }

        @Override
        public void run() {
            //  synchronized (obj) {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " start");
                for (int i = 1; i <= 10; i++) {
                    System.out.println(i);
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (i == 5) {
                        throw new RuntimeException("异常!!!");
                    }
                }
                System.out.println(Thread.currentThread().getName() + " end");
            } finally {
                lock.unlock();
            }
            //   }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object obj = new Object();
        T t = new T(obj);
        Runnable target;
        Thread th = new Thread(t);
        Thread th2 = new Thread(t);
        th.start();
        Thread.sleep(1000);
        th2.start();
    }
}
